<template>
    <div class="uploader">
        <el-row v-if="canUpload" :style="{ marginBottom: '15px' }">
            <el-col :span="24">
                <el-upload multiple :action="uploadApi" :headers="{ Authorization: authToken }" :on-success="handleUploadSuccess" :show-file-list="false" :accept="acceptFileTypes" :before-upload="handleBeforeUpload">
                    <el-button size="small" type="primary">选择上传文件</el-button>
                </el-upload>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="24">
                <div class="attach-list">
                    <div class="attach-item" v-for="(item, index) in files" :key="index">
                        <file-item :file="item" :width="width" />
                        <div class="attach-handles">
                            <el-button size="small" type="text" @click="handleDownload(item)">下载</el-button>
                            <el-button v-if="canDelete" size="small" type="text" @click="handleDel(item)">删除</el-button>
                        </div>
                    </div>
                </div>
            </el-col>
        </el-row>
    </div>
</template>
<script>
import { getToken } from "@/utils/auth";
import FileItem from "./fileItem.vue";

export default {
    name: "Uploader",
    props: {
        files: {
            type: Array,
            default: [],
        },
        canUpload: {
            type: Boolean,
            default: true,
        },
        canDelete: {
            type: Boolean,
            default: false,
        },
        width: {
            type: String,
            default: "178px",
        },
    },
    components: { FileItem },
    data() {
        return {
            acceptFileTypes: "image/*,.pdf,.doc,.docx,.xls,.xlsx,.csv,.ppt,.pptx,.txt,.zip,.rar,video/*,audio/*",
        };
    },
    computed: {
        uploadApi() {
            return process.env.VUE_APP_BASE_API + "/com/ComAttach";
        },
        authToken() {
            return "Bearer " + getToken();
        },
    },
    methods: {
        handleUploadSuccess(response, file, fileList) {
            this.$modal.closeLoading();
            this.$emit("uploading", response.data);
        },
        handleDownload(data) {
            this.$emit("onDownload", data);
        },
        handleDel(data) {
            this.$emit("onRemove", data);
        },
        handleBeforeUpload() {
            this.$modal.loading("正在上传文件，请稍后...");
        },
    },
};
</script>
<style lang="scss" scoped>
.attach-list {
    display: flex;
    flex-flow: row;

    .attach-item {
        margin-right: 10px;
        display: flex;
        flex-flow: column;

        .attach-handles {
            text-align: center;
        }
    }
}
</style>
